package com.rd.p2p.app.account;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.AccountBankService;
import com.qdlc.p2p.biz.service.AccountLogService;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.AdditionalUserDrawLotteryService;
import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.biz.service.BorrowCollectionService;
import com.qdlc.p2p.biz.service.BorrowTenderService;
import com.qdlc.p2p.biz.service.DictService;
import com.qdlc.p2p.biz.service.NewActivityPlanService;
import com.qdlc.p2p.biz.service.NewActivityRuleService;
import com.qdlc.p2p.biz.service.TppAccountService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserInviteService;
import com.qdlc.p2p.biz.service.UserPwdQuestionService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.service.UserSignService;
import com.qdlc.p2p.biz.util.ActivityTools;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.enums.EnumActicityPlanNid;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.code.BASE64Encoder;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dao.AdditionalDrawLotteryRuleDao;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.AccountBank;
import com.qdlc.p2p.dal.dto.AdditionalDrawLotteryRule;
import com.qdlc.p2p.dal.dto.AdditionalUserDrawLottery;
import com.qdlc.p2p.dal.dto.Dict;
import com.qdlc.p2p.dal.dto.NewActivityPlan;
import com.qdlc.p2p.dal.dto.NewActivityRule;
import com.qdlc.p2p.dal.dto.TppAccount;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.dto.UserSign;
import com.qdlc.p2p.dal.model.AccountBankModel;
import com.qdlc.p2p.dal.model.AppMemberModel;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;
import com.qdlc.p2p.dal.model.UserInviteModel;
import com.qdlc.p2p.dal.util.UserUtils;

public class AppMemberAction extends BaseAction<AppMemberModel> implements ModelDriven<AppMemberModel> {

	@Resource
	private UserService userService;

	@Resource
	private UserInviteService userInviteService;
	@Resource
	private UserSignService userSignService;
	@Resource
	private AccountService accountService;
	@Resource
	private AccountLogService accountLogService;
	@Resource
	private BorrowTenderService borrowTenderService;
	@Resource
	private TppAccountService tppAccountService;
	@Resource
	private UserIdentifyService userIdentifyService;
	@Resource
	private UserPwdQuestionService userPwdQuestionService;
	@Resource
	private AccountBankService accountBankService;
	@Resource
	private NewActivityPlanService newActivityPlanService;
	@Resource
	private NewActivityRuleService newActivityRuleService;
	@Resource
	private AdditionalDrawLotteryRuleDao additionalDrawLotteryRuleDao;
	@Resource
	private BorrowCollectionService borrowCollectionService;
	@Resource
	private  DictService dictServic;

	@Resource
	private AdditionalUserDrawLotteryService additionalUserDrawLotteryService;
	private Map<String, Object> data;

	@Action("/app/member/info")
	public void memberInfo() throws IOException {
		User user = getSessionUser();
		data = new HashMap<String, Object>();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}
		// 更新下userIdentify缓存
		UserIdentify userIdentify = userIdentifyService.findByUserId(user.getUserId());
		session.put(Constant.SESSION_USER_IDENTIFY, userIdentifyService.findById(userIdentify.getId()));
		data.put("realNameStatus", userIdentify.getRealNameStatus());
		user = userService.find(getSessionUserId());
		// 判断交易密码是否已设置
		data.put("hasPayPwd", StringUtils.isNotBlank(user.getPayPwd()));
		data.put("user", user);
		List<AccountBank> bankList = accountBankService.list(user.getUserId());
		data.put("bindingBank", (bankList != null) && (bankList.size() > 0));
		printWebJson(getStringOfJpaObj(data));
	}

	@Action("/app/member/memberInfo")
	public void userMemberInfo() throws IOException {
		User user = getSessionUser();
		data = new HashMap<String, Object>();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}
		// 更新下userIdentify缓存
		UserIdentify userIdentify = UserUtils.getUserIdentify(user.getUserId());
		data.put("realNameStatus", userIdentify.getRealNameStatus());
		user = userService.find(getSessionUserId());
		String avatarPicPath= UserUtils.getUserCacheByUserId(user.getUserId()).getAvatarPicPath();
		User userDisplay = new User();
		userDisplay.setUserName(user.getUserName());
		userDisplay.setEmail(user.getEmail());
		userDisplay.setRealName(user.getRealName());
		userDisplay.setCardId(user.getHideCardId());
		userDisplay.setMobilePhone(user.getMobilePhone());
		// 判断交易密码是否已设置
		data.put("hasPayPwd", StringUtils.isNotBlank(user.getPayPwd()));
		data.put("user", userDisplay);
		data.put("avatarPicPath", avatarPicPath);

		List<AccountBank> bankList = accountBankService.list(user.getUserId());
		List<AccountBankModel> accountBankModelList = new ArrayList<AccountBankModel>();
		for (AccountBank accountBank : bankList) {
			AccountBankModel accountBankModel = AccountBankModel.instance(accountBank);
			Dict dict = dictServic.find(accountBank.getBank());
			accountBankModel.setBankName(dict.getName());
			accountBankModelList.add(accountBankModel);
		}
		data.put("bankList",accountBankModelList);
		data.put("bindingBank", (bankList != null) && (bankList.size() > 0));
		printWebJson(getStringOfJpaObj(data));
	}


	/**
	 * 资金统计信息
	 * 
	 * @throws Exception
	 */
	@Action("/app/member/investHandleMoney")
	public void investHandleMoney() throws Exception {
		data = new HashMap<String, Object>();
		User user = getSessionUser();
		if(null==user){
			printWebResCodeAndMsgResult("-1","用户尚未登陆");
			return;
		}
		int signStatus = isSignLottery();
		data.put("signStatus", signStatus);
		Account account = accountService.findAccountByUserId(user.getUserId());
		data.put("account", account);
		//待收利息
		double interest =borrowCollectionService.getInterestByUser(user);
		data.put("interest", interest);
		//待收本金
		double capital = borrowCollectionService.getCapitalByUser(user);
		data.put("capital", capital);
		// 今日净收益
		double todayEarnAmount = accountLogService.todayEarnAmount(user.getUserId());
		data.put("todayEarnAmount", todayEarnAmount);
		// 累计净收益
		double earnAmount = accountLogService.earnAmount(user.getUserId());
		data.put("earnAmount", earnAmount);

		//今日日期
		Date today = DateUtil.getNow();
		//获取当月第一天
		Date monthFirstDay=DateUtil.currMonthFirstDay(today);
		//获取今年的第一天
		Date yearFirstDay = DateUtil.getCurrYearFirstDay();
		//获取这个季度的第一天
		Date quarterFirstDay = DateUtil.getCurrentQuarterStartTime();

		/*//月累计收益
		double monthEarnAmount = accountLogService.earnAmount(user.getUserId(),monthFirstDay,today);
		data.put("monthEarnAmount", monthEarnAmount);

		//季度累计收益
		double quarterEarnAmount =  accountLogService.earnAmount(user.getUserId(),quarterFirstDay,today);
		data.put("quarterEarnAmount", quarterEarnAmount);

		//年累计收益
		double yearEarnAmount= accountLogService.earnAmount(user.getUserId(),yearFirstDay,today);
		data.put("yearEarnAmount", yearEarnAmount);*/

		// 在投金额
		double investIngAmount = borrowTenderService.investIngAmount(user.getUserId());
		data.put("investIngAmount", investIngAmount);
		// 累计投资
		double investAmount = borrowTenderService.investAmount(user.getUserId());
		data.put("investAmount", investAmount);
		// 新浪存钱罐收益
		TppAccount tppAccount = tppAccountService.findByUser(user.getUserId());
		data.put("tppAccount", tppAccount);
		printWebJson(getStringOfJpaObj(data));
	}

	/**
	 * 判断用户是否可以签到
	 *
	 * @return
	 */
	public int isSignLottery() throws Exception {
		data = new HashMap<String, Object>();
		User user = getSessionUser();
		if (user == null) {
			throw new UserException("请登录", BusinessException.TYPE_JSON);
		}

		UserSign userSign = userSignService.findLastRecord(user.getUserId());
		if ((userSign == null)
				|| !ActivityTools.getCurrentDate().equals(ActivityTools.format(userSign.getSignTime()))) {
			return 0;
			// 签到抽奖状态：1已签到未抽奖，2已抽奖，0未签到
			// 今天已经签到：再判断是否已经抽奖
		} else {
			// 判断有没有抽奖机会，就算不是今天的也可以
			AdditionalUserDrawLottery additionalUserDrawLottery = additionalUserDrawLotteryService
					.getValidDrawLotteryByUserId(user.getUserId());
			return additionalUserDrawLottery.getId() != 0 ? 1 : 2;
		}
	}

	@Action("/app/member/getSignStatus")
	public String getSignStatus() throws Exception {
		int signStatus = isSignLottery();
		data.put("signStatus", signStatus);
		printWebJson(getStringOfJpaObj(data));
		return null;
	}

	/**
	 * 用户签到
	 *
	 * @return
	 */
	@Action("/app/member/sign")
	public void doSign() throws Exception {
		if (getSessionUser() == null) {
			throw new UserException("请登录", BusinessException.TYPE_JSON);
		}
		data = new HashMap<String, Object>();
		User user = getSessionUser();
		UserSign userSign = userSignService.findLastRecord(user.getUserId());
		// 用户今天签到过了
		if ((userSign != null) && ActivityTools.getCurrentDate().equals(ActivityTools.format(userSign.getSignTime()))) {
			data.put("result", false);
			printWebJson(getStringOfJpaObj(data));
			return;
		}
		// 用户昨天签到
		if ((userSign != null) && ActivityTools.getPreDate().equals(ActivityTools.format(userSign.getSignTime()))) {
			// 赠送签到活动对应规则
			recordUserSign(user, userSign.getSignDayCount() + 1);
			data.put("result", true);
		} else {
			// 赠送签到活动对应规则
			recordUserSign(user, 1);
			data.put("result", true);
		}
		// 活动方案执行
		try {
			signActivityPlan(user.getUserId(), EnumActicityPlanNid.SIGN.getValue());
		} catch (Exception e) {
			e.printStackTrace();
		}
		printWebJson(getStringOfJpaObj(data));
	}

	/**
	 * 记录用户签到
	 *
	 * @param user
	 * @param signDayCount
	 */
	private void recordUserSign(User user, int signDayCount) {
		UserSign userSign = new UserSign();
		userSign.setSignIp(getRequestIp());
		userSign.setAddTime(new Date());
		userSign.setSignDayCount(signDayCount);
		userSign.setSignTime(new Date());
		userSign.setDescription("用户签到");
		userSign.setUserId(user.getUserId());
		userSignService.save(userSign);
	}

	/**
	 * 签到活动
	 *
	 * @param userId
	 * @param type
	 * @return
	 */
	private void signActivityPlan(long userId, String type) {
		NewActivityPlan activityPlan = newActivityPlanService.getActivityPlanByTache(type);
		// 校验本活动是否可用
		boolean isAvailable = ActivityTools.checkActivity(activityPlan, userId);
		if (!isAvailable) {
			return;
		}
		// 查询活动规则表，如果为空直接返回
		List<NewActivityRule> list = newActivityRuleService.findByActivityId(activityPlan.getId());
		if ((null == list) || list.isEmpty()) {
			return;
		}
		for (NewActivityRule entity : list) {
			// 校验本条规则是否可用
			if (!ActivityTools.checkRule(entity, userId)) {
				continue;
			}
			String serviceBeanName = entity.getBusinessClass();
			if (serviceBeanName.equals("giveUserLotteryService")) {
				// 判断规则存在+判断状态 0:启用 1:未启用
				AdditionalDrawLotteryRule additionalDrawLotteryRule = additionalDrawLotteryRuleDao
						.find(entity.getRuleId());
				if ((additionalDrawLotteryRule == null) || (additionalDrawLotteryRule.getStatus() != 0)) {
					continue;
				}
				// 抽奖规则不满足条件的过滤掉
				UserSign userSign = userSignService.findLastRecord(userId);
				int continueCount = additionalDrawLotteryRule.getContinueCount();
				// 如果规定连续动作为1每次都送，如果规定连续动作大于1就需要签到天数=连续动作
				if ((continueCount > 1) && (userSign.getSignDayCount() != continueCount)) {
					continue;
				}
			}
			BaseGiveAwardService baseGiveAwardService = (BaseGiveAwardService) BeanUtil.getBean(serviceBeanName);
			BaseGiveAwardModel baseGiveAwardModel = new BaseGiveAwardModel();
			baseGiveAwardModel.setUser(getSessionUser());
			baseGiveAwardModel.setRuleId(entity.getRuleId());
			baseGiveAwardModel.setSourceType(type);
			baseGiveAwardModel.setRuleType(entity.getType());
			baseGiveAwardModel.setDescription("签到活动");
			baseGiveAwardService.giveAward(baseGiveAwardModel);
		}
	}


	/**
	 * 回款日历接口
	 *
	 * @throws Exception
	 */
	@Action("/app/member/collectionCalendar")
	public void collectionCalendar() throws Exception {
		data = new HashMap<String, Object>();
		User user = getSessionUser();
		if(null==user){
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}

		String date = paramString("date");

		long userId = user.getUserId();
		List<Object[]> list = borrowCollectionService.getInterestByMonth(userId,date);
		double amountInterest = borrowCollectionService.getAmountInterestByMonth(userId,date);
		double amountRepayment = borrowCollectionService.getAmountRepaymentByMonth(userId, date);

		data.put("resCode", "1");
		data.put("resMsg", "请求成功");
		data.put("list", list);
		data.put("amountInterest", amountInterest);
		data.put("amountRepayment",amountRepayment);
		printWebJson(getStringOfJpaObj(data));
		return;
	}

}
